package com.hh85.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.HashMap;

public class DatabaseUtils {
    private Context context;
    public SQLiteDatabase mSQLiteDatabase = null;
    private DatabaseHelper mDatabaseHelper = null;
    private String dbName;
    public DatabaseUtils(Context context,String dbName){
        this.context = context;
        this.dbName = dbName;
    }

    class DatabaseHelper extends SQLiteOpenHelper{

        public DatabaseHelper(Context context, String dbName, SQLiteDatabase.CursorFactory factory, int version){
            super(context,dbName,factory,version);
        }
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {

            String sql = "create table account(_id INTEGER PRIMARY KEY AUTOINCREMENT,acid varchar(50),price int,remark varchar(255),type varchar(20),time varchar(20))";

            sqLiteDatabase.execSQL(sql);
        }
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        }
    }

    public  void open(){
        mDatabaseHelper = new DatabaseHelper(context,dbName,null,1);
        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
    }
    // 关闭数据库
    public void close() {
        mDatabaseHelper.close();
    }
    public long insert(String tabName, HashMap<String,String> param){

            ContentValues cv = new ContentValues();
            for (String key:param.keySet()){
                cv.put(key,param.get(key));
            }

            return mSQLiteDatabase.insert(tabName, null, cv);



    }

    public Cursor select(String sql,String[] bindArgs){

            return mSQLiteDatabase.rawQuery(sql, bindArgs);



    }
    public Cursor query(String tableName, String sqlString) {

        synchronized (mDatabaseHelper) {
            SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
            Cursor cursor = database.rawQuery("select * from " + tableName + " " + sqlString, null);

            return cursor;
        }
    }

    public void querySql(String sql){
             mSQLiteDatabase.execSQL(sql);
    }

    public void update(String tabName,HashMap<String,String> param,String whereClause, String[] whereArgs){
        ContentValues cv = new ContentValues();
        for (String key:param.keySet()){
            cv.put(key,param.get(key));
        }
        mSQLiteDatabase.update(tabName,cv,whereClause,whereArgs);
    }
    public int delete(String tabName,String whereClause, String[] whereArgs){

        return   mSQLiteDatabase.delete(tabName, whereClause, whereArgs);

    }
}
